package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getCode);
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }

    @PutMapping
    @CacheEvict(value = "setmealCache", key = "#setmealDto.categoryId+'_'+#setmealDto.status")
    public R update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithFlavor(setmealDto);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    //修改状态
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R updateStatus(@PathVariable int status, @RequestParam List<Long> ids) {
        log.info("status {} 和 ids {} ", status, ids);
        setmealService.updateStatus(status, ids);
        return R.success("修改成功");
    }

    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R delete(@RequestParam List<Long> ids) {
        if (ids != null && ids.size() > 0) {
            setmealService.removeWithDish(ids);
            return R.success("删除成功");
        }
        return R.error("请选择要删除的套餐");
    }

    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        setmealLqw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, setmealLqw);

        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        List<Setmeal> setmealList = setmealPage.getRecords();
        if (setmealList.size() > 0) {
            List<Long> categoryIdList = setmealList.stream().map(item -> item.getCategoryId()).distinct().collect(Collectors.toList());
            List<Category> categories = categoryService.listByIds(categoryIdList);

            Map<Long, String> categoryMap = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));

            List<SetmealDto> collect = setmealList.stream().map(item -> {
                SetmealDto setmealDto = new SetmealDto();
                BeanUtils.copyProperties(item, setmealDto);
                setmealDto.setCategoryName(categoryMap.get(item.getCategoryId()));
                return setmealDto;
            }).collect(Collectors.toList());

            setmealDtoPage.setRecords(collect);
        }

        return R.success(setmealDtoPage);
    }

    @PostMapping
    @CacheEvict(value = "setmealCache", key = "#setmealDto.categoryId+'_1'")
    public R save(@RequestBody SetmealDto setmealDto) {
        log.info("接收到{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("添加成功");
    }
}
